package com.wenqiner.requesttool.core.thread;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;

/**
 * @author rhf
 * @date 2023-03-28
 **/
public class FixedTaskExecutor<T> extends ThreadTemplate {

    public static final Logger log = LoggerFactory.getLogger(FixedTaskExecutor.class);

    private final BlockingQueue<T> queue = new ArrayBlockingQueue<>(1000);
    private final Consumer<T> consumer;



    public FixedTaskExecutor(Consumer<T> consumer) {
        this.consumer = consumer;
        Thread thread = getCustomerThread(this::execute, Thread.MIN_PRIORITY);
        thread.start();
    }


    public void execute() {
        try {
            for (;;)
            {
                T data = queue.take();
                consumer.accept(data);
            }
        } catch (Exception e) {
            log.error("获取阻塞队列中数据执行方法异常,error msg:[{}], \ne:{}",e.getMessage(), e);
        }
    }

    public void push(T t){
        queue.add(t);
    }

}
